/*
 * Copyright © 2024-2025 Wenze Wei
 *
 * This file is part of StadionOS.
 *
 * This Source Code Form is subject to the terms of the GNU General Public License, v. 2.0.
 * You can obtain a copy of the GPL at
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 */

#include "../include/fsd.h"

/**
 * @brief Writes data to a file descriptor.
 *
 * This function writes up to 'count' bytes from 'buf' to the file descriptor 'fd'.
 * It performs error checking on 'count', 'fd', and 'buf' to ensure they are valid.
 *
 * @param fd The file descriptor to write to.
 * @param buf The buffer containing the data to write.
 * @param count The number of bytes to write.
 * @return ssize_t The number of bytes written, or -1 on error.
 */
ssize_t Swrite(int fd, const void *buf, size_t count) {  
    if (count == 0)
        return 0;

    if (fd < 0)
        return -1;
 
    if (buf == NULL)
        return -1;

    ssize_t bytes_written = syscall(SYS_write, fd, buf, count);  

    if (bytes_written == -1)
        return -1;

    return bytes_written;
}

/**
 * @brief Writes a key-value pair to a file (FOR SYSTEM COMPONENTS ONLY).
 *
 * This function writes the key-value pair to the file specified by 'file'.
 * It opens the file in append mode and writes the formatted string "key=value\n" to the file.
 * IMPORTANT: This function is critical and should only be used by system components.
 *
 * @param file The path of the file to write to.
 * @param key The key to write.
 * @param value The value to write.
 * @return int 0 on success, or -1 on error.
 */
int SXwrite(const char *file, const char *key, const char *value) {
    ssize_t fd = SXopen(file, "a", 0666);
    if (fd == -1)
        return -1;

    char buffer[512];
    int len = snprintf(buffer, sizeof(buffer), "%s=%s\n", key, value);

    if (Swrite(fd, buffer, len) < 0) {
        Sclose(fd);
        return -1;
    }

    Sclose(fd);
    return 0;
}